<template>
  <div class="flex jc ac">
    <div ref="lottieContainerEle" :style="lottieContainerStyle"></div>
  </div>
</template>

<script lang="ts" setup>
/**
 * 导入类型声明
 */
import { CSSProperties } from 'vue';

/**
 * 定义props的类型声明
 */
interface Props {
  /**
   * 容器宽度
   */
  width?: number;

  /**
   * 容器高度
   */
  height?: number;

  /**
   * 动画地址
   */
  url?: string;
}

/**
 * 定义props
 */
const props = defineProps<Props>();

/**
 * 定义容器
 */
const lottieContainerEle = useTemplateRef<HTMLDivElement | null>('lottieContainerEle');

/**
 * 容器样式
 */
const lottieContainerStyle = computed(() => {
  const styles: CSSProperties = {
    width: '100%',
    height: '100%',
  };
  if (props.width && props.height) {
    styles.width = `${props.width}px`;
    styles.height = `${props.height}px`;
  }
  return styles;
});

/**
 * 初始化lottie动画
 */
const setupLottieWeb = async (): Promise<void> => {
  await nextTick();
  if (!lottieContainerEle.value) {
    return;
  }
  const lottieParams: AnimationConfig = {
    container: lottieContainerEle.value,
    renderer: 'svg',
    loop: true,
    autoplay: true,
    path: props.url,
  };
  lottie.loadAnimation(lottieParams);
};

/**
 * 监听地址变化
 */
watch(
  () => props,
  () => {
    setupLottieWeb();
  },
  {
    immediate: true,
  },
);
</script>
